import csv
from file_manager import *
import json


def remove_redundant_rows():
    translated_folder_name = "translated"
    pathes = get_new_pull_file_pathes(translated_folder_name)
    for new_file_path in pathes:
        print(new_file_path)
        with open(new_file_path, 'r', encoding='utf-8') as csvfile:
            files = csv.reader(csvfile)
            current_rows_dic = {}
            current_rows = []
            for row in files:
                if len(row) < 3:
                    print("less than", row)
                    continue
                if is_duplicate_key(current_rows_dic, row[0].strip()) and len(row[1].strip()) <= 0:
                    print("filter:", row[0])
                    continue
                current_rows_dic[row[0].strip()] = {"zh": row[1].strip(), "tips": row[2].strip()}

            for key in current_rows_dic.keys():
                current_rows.append([key, current_rows_dic[key]['zh'], current_rows_dic[key]['tips']])

            with open(new_file_path, 'w') as csvfile:
                writer = csv.writer(csvfile)
                for row in current_rows:
                    if len(row) != 3:
                        print('XXXX', row)
                    writer.writerow(row)

# check if translated files are correct， the row count should be 0 or 3
def check_translated_count():
    translated_folder_name = "translated"
    pathes = get_new_pull_file_pathes(translated_folder_name)
    for new_file_path in pathes:
        print(new_file_path)
        with open(new_file_path) as csvfile:
            reader = csv.reader(csvfile)
            for row in reader:
                if len(row) != 3:
                    print(len(row), row)
        # with open(new_file_path, 'r', encoding='utf-8') as csvfile:
        #     files = csv.reader(csvfile)
        #     for row in files:
        #         print(len(row), row[0])

# 获取新拉取内容文件的路径
def get_new_pull_file_pathes(main_folder: str) -> []:
    # 检查content文件夹是否存在
    if not is_file_exist(main_folder):
        print("content文件夹不存在")
        return []
    pathes = []
    # 遍历content下的文件夹
    for root, dirs, files in os.walk(main_folder):
        for folder in dirs:
            folder_path = os.path.join(root, folder)
            csv_files = [f for f in os.listdir(folder_path) if f.endswith('.csv')]
            # 如果里面有csv文件
            if csv_files:
                for csv_file in csv_files:
                    file_path = os.path.join(folder_path, csv_file)
                    pathes.append(file_path)
    return pathes

def add_csv_header():
    translated_folder_name = "translated"
    pathes = get_new_pull_file_pathes(translated_folder_name)
    header = ['Key', 'Translation', 'Tips']
    for new_file_path in pathes:
        with open(new_file_path, 'r', encoding='utf-8') as csvfile:
            files = csv.reader(csvfile)
            current_rows = [row for row in files]
        current_rows.insert(0, header)

        with open(new_file_path, 'w') as csvfile:
            writer = csv.writer(csvfile)
            for row in current_rows:
                writer.writerow(row)



def regenerate_files():
    content_folder_name = "contents"
    translated_folder_name = "translated"
    json_folder_name = "json"
    js_folder_name = "js"
    pathes = get_new_pull_file_pathes(content_folder_name)
    for new_file_path in pathes:
        # 1. 添加新的key到translated文件
        translated_file_path = new_file_path.replace(content_folder_name, translated_folder_name)
        # remove suffix '.csv'
        json_file_path = new_file_path.replace(content_folder_name, json_folder_name)[:-4]
        js_folder_path = new_file_path.replace(content_folder_name, js_folder_name)[:-4]
        # 2. 将translated文件转化成json
        create_new_json_file(translated_file_path, json_file_path)
        # 3. 将json转化成js
        create_js_file(json_file_path, js_folder_path)

def create_js_file(json_file_path, js_file_path):
    os.makedirs(os.path.split(js_file_path)[0], exist_ok=True)
    with open(json_file_path, 'r', encoding='utf-8') as json_file:
        json_content = json.load(json_file)

    # 将JSON转换为字符串，并将其作为变量嵌入到JavaScript函数字符串中
    content = f"function handleCallback() {{ return {json.dumps(json_content, ensure_ascii=False)}; }}"
    with open(js_file_path, 'w', encoding='utf8') as jf:
        jf.write(content)

def create_new_json_file(translated_file_path, json_file_path):
    os.makedirs(os.path.split(json_file_path)[0], exist_ok=True)
    print(translated_file_path)
    with open(translated_file_path, 'r') as f:
        reader = csv.reader(f)
        next(reader)
        data = {rows[0]: {"zh": rows[1].strip(), "tips": rows[2]} for rows in reader if len(rows) >= 3}
        json_data = json.dumps(data, ensure_ascii=False)
        with open(json_file_path, 'w', encoding='utf8') as jf:
            jf.write(json_data)


def is_duplicate_key(my_dict, key):
    if key in my_dict:
        return True
    else:
        return False